<%--
  Created by IntelliJ IDEA.
  User: Wanghaha
  Date: 2019/11/19
  Time: 11:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<%@ include file="/head.jsp" %>
<body>


<div class="layui-tab" lay-filter="test1">
    <ul class="layui-tab-title">
        <li class="layui-this" lay-id="111">创建课程</li>
        <li lay-id="222">添加到讲师已有课程</li>
    </ul>
    <div class="layui-upload">
        <video style="display: none" id="videoattr" width="250" height="100" ></video>
        <div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                <tr>
                    <th>视频名</th>
                    <th>大小</th>
                    <th>排序</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="demoList"></tbody>
            </table>
        </div>
        <button style="margin-left: 20px" type="button" class="layui-btn layui-btn-normal" id="testList">选择视频</button>
    </div>

    <div class="layui-tab-content" >
        <div class="layui-tab-item layui-show">
            <form class="layui-form"  method="get" id="saveVideoInfoFrom">
                <input type="hidden" name="userId" value="${data['userInfoVos'][0].userId}">
<%--                <label style="display: none" id="videoId">1</label>--%>
                <div class="layui-form-item">
                    <label class="layui-form-label">讲师昵称:</label>
                    <div class="layui-input-block">
                        <input type="text" readonly class="layui-input" name="userName" value="${data['userInfoVos'][0].userNickName}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">讲师简介:</label>
                    <div class="layui-input-block">
                        <input type="text" readonly class="layui-input" name="userDesc" value="${data['userInfoVos'][0].userDesc}">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">课程标题:</label>
                    <div class="layui-input-block">
                        <input type="text" id="videoName"  name="videoName" lay-verify=“required“ lay-verify="required" placeholder="请输入标题"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">课程简介:</label>
                    <div class="layui-input-block">
                        <input type="text" required lay-verify="required"  class="layui-input" name="videoDesc">
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label">封面图片:</label>
                    <span style="display: none" id="videoImgSpan"></span>
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-normal" id="videoImg">选择文件</button>
                        <img class="layui-upload-img" height="70" width="100" id="previewImg">
                    </div>
                </div>
<%--                <div class="layui-form-item layui-form-text">--%>
<%--                    <label class="layui-form-label">课程概述：</label>--%>
<%--                    <div class="layui-input-block">--%>
<%--                        <textarea name="videoDesc" placeholder="请输入内容" class="layui-textarea"></textarea>--%>
<%--                    </div>--%>
<%--                </div>--%>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">一级分类：</label>
                    <div class="layui-input-block">
                        <select name="stIdOne" id="stIdOne" lay-filter="demo">
                            <option value="0">请选择一级分类</option>
                            <c:forEach items="${type}" var="item">
                                <option value="${item.stId}">${item.stName}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">二级分类：</label>
                    <div class="layui-input-block">
                        <select name="stIdTwo" id="stIdTwo">
                            <option value="0">请选择二级分类</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label" >是否免费：</label>
                    <div class="layui-input-block" id="isFree">
                        <input type="radio"   name="isFree" value="1" title="是" lay-filter="isFree"/>
                        <input type="radio" checked name="isFree" value="0" title="否" lay-filter="isFree"/>
                    </div>
                </div>
                <div class="layui-form-item" id="price">
                    <label class="layui-form-label">价格:</label>
                    <div class="layui-input-block">
                        <input   name="originalPrice" type="number" value="0" step="0.01"  autocomplete="off"  class="layui-text" lay-verify="required" >
                    </div>
                    <div class="layui-form-mid layui-word-aux">若选择收费，平台将会收取10%的服务费。</div>
                </div>
                <div class="layui-form-item" id="publishType">
                    <label class="layui-form-label">发布类型:</label>
                    <div class="layui-input-block">
                        <input type="radio" checked  name="publishType" value="1" title="立即发布" lay-filter="publishType"/>
                        <input type="radio"  name="publishType" value="2" title="待讲师发布" lay-filter="publishType"/>
                    </div>
                </div>

            </form>
        </div>
        <div class="layui-tab-item">
            <form class="layui-form" action="post">
                <input type="hidden" name="userId" value="${data['userInfoVos'][0].userId}">
                <div class="layui-form-item">
                    <label class="layui-form-label">讲师昵称:</label>
                    <div class="layui-input-block">
                        <input type="text" readonly name="teacherName" value="${data['userInfoVos'][0].userNickName}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">讲师课程:</label>
                    <div class="layui-input-block">
                        <select name="videoId" lay-filter="selectVideos">
                            <option selected  value="-1">请选择讲师课程</option>
                            <c:forEach items="${data['userInfoVos'][0].videosVos}" var="item">
                                <option  value="${item.videoId}">${item.videoName}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">

                    <table id="sea" lay-filter="sea"></table>

                </div>

            </form>
        </div>
    </div>
    <button style="margin-left: 20px;display: none" type="submit" class="layui-btn" id="testListAction">开始上传</button>
</div>
<%--<button style="margin-left: 20px" type="submit" class="layui-btn" id="click">开始上传</button>--%>
<button style="margin-left: 20px" type="submit" class="layui-btn" id="submit">提交</button>

<input name="addVideoItemUrlData" id="addVideoItemUrlData" hidden value="">


<script>
    $("#submit").click(function () {
        //获取tab标识
        var layid = location.hash.replace(/^#test1=/, '');
        var videoName = $('input[name="videoName"]').val();
        var videoDesc = $('input[name="videoDesc"]').val();
        var demoListView = $('#demoList').html();
        var videoImg =  $('#videoImgSpan').text();
        var stIdOne = $('select[name="stIdOne"]').val();
        var stIdTwo = $('select[name="stIdTwo"]').val();
        var addVideoItemUrlData = $("#addVideoItemUrlData").val();
        var tableData = layui.table.cache['sea'];
        var names = $("div[name='name']");
        var sorts = $("div[name='sort']");
        var addVideoItem = [];
        names.each(function (index) {
            addVideoItem.push({
                videoItemName:$(this).html(),
                sort:sorts.eq(index).html()
            })
        });

        if ("" == demoListView){
            alert("请上传视频！！！");
            return;
        }else{
            if ( layid == 111 || layid ==''){
                if ("" == videoName){
                    alert("课程标题不能为空！！!");
                    return;
                }else if("" == videoDesc){
                    alert("课程简介不能为空!!!");
                    return;
                }else if("" == videoImg){
                    alert("请选择封面图片!!!");
                    return;
                }else if(0 == stIdOne){
                    alert("请选择一级分类!!!");
                    return;
                }else if(0 == stIdTwo){
                    alert("请选择二级分类!!!");
                    return;
                }
                $.ajax({
                    url: '/manage/videos/uploadFileToOSS',
                    dataType: 'json',
                    type: 'post',
                    data:{videoName:videoName,
                        videoDesc:videoDesc,
                        videoImg:videoImg,
                        stIdOne:stIdOne,
                        stIdTwo:stIdTwo,
                        teacherName: $('input[name="teacherName"]').val(),
                        userDesc: $('input[name="userDesc"]').val(),
                        isFree: 0+$('input[name="isFree"]:checked').val(),
                        publishType: 0+$('input[name="publishType"]:checked').val(),
                        videoId:  $('select[name="videoId"]').val(),
                        userId: $('input[name="userId"]').val(),
                        updateVideoItem : JSON.stringify(tableData),
                        addVideoItem : JSON.stringify(addVideoItem),
                        addVideoItemUrlData : addVideoItemUrlData
                        },
                    success: function (data) {
                        if (data.code==200){
                            layer.msg(data.msg,{icon: 1, time: 500},function () {
                                layer.close();
                                window.parent.location.reload();
                            });
                        }else{
                            layer.msg(data.msg,{icon: 2, time: 1000});
                        }
                    }
                })
        }else if (layid == 222){
                var videoId  = $('select[name="videoId"]').val();
                if (videoId == -1){
                    alert("请选择课程");
                    return;
                }
                $.ajax({
                    url: '/manage/videos/uploadFileToOSS',
                    dataType: 'json',
                    type: 'post',
                    data:{
                        videoId:  $('select[name="videoId"]').val(),
                        userId: $('input[name="userId"]').val(),
                        updateVideoItem : JSON.stringify(tableData),
                        addVideoItem : JSON.stringify(addVideoItem),
                        addVideoItemUrlData : addVideoItemUrlData
                    },
                    success: function (data) {
                        if (data.code==200){
                            layer.msg(data.msg,{icon: 1, time: 500},function () {
                                layer.close();
                                window.parent.location.reload();
                            });
                        }else{
                            layer.msg(data.msg,{icon: 2, time: 1000});
                        }
                    }
                })
            }
        }

    })
</script>

<script>
    $(function () {
        $("#click").click(function () {
            //获取tab标识
            var layid = location.hash.replace(/^#test1=/, '');
            var  videoName = $('input[name="videoName"]').val();
            var videoDesc = $('input[name="videoDesc"]').val();
            var demoListView = $('#demoList').html();
            var videoImg =  $('#videoImgSpan').text();
            var stIdOne = $('select[name="stIdOne"]').val();
            var stIdTwo = $('select[name="stIdTwo"]').val();
            if ("" == demoListView){
                alert("请上传视频！！！");
            }else{
                if ( layid == 111 ){
                    if ("" == videoName){
                        alert("课程标题不能为空！！!");
                    }else if("" == videoDesc){
                        alert("课程简介不能为空!!!");
                    }else if("" == videoImg){
                        alert("请选择封面图片!!!");
                    }else if(0 == stIdOne){
                        alert("请选择一级分类!!!");
                    }else if(0 == stIdTwo){
                        alert("请选择二级分类!!!");
                    }else{
                        $("#testListAction").click();
                    }
                }else if (layid == 222){
                    var videoId  = $('select[name="videoId"]').val();
                    if (videoId == -1){
                        alert("请选择课程");
                        return;
                    }
                    $("#testListAction").click();
                }
            }

        })



        layui.use(['layer', 'jquery', 'form'], function () {
            var layer = layui.layer,
                $ = layui.jquery,
                form = layui.form;


               form.on('radio(isFree)', function (data) {
                   console.log($('input[name="videoImg"]').val());

                   if ($("input[name='isFree']:checked").val() == 1){
                       $("#price").hide();
                   }else{
                       $("#price").show();
                   }
                   form.render();

               });

            form.on('select(videoId)', function(data){
                var video = $('select[name="stIdTwo"]').val();
                $("#videoId").html(video);
                console.log(this.val());
            });
            $("#videoName").blur(function(){
                $('#videoId').html("0");
                console.log($('#videoId').html());
            })

            form.on('input(videoImg)', function(data){
                console.log(this.val());
            });
               form.on('select(demo)', function(data){
                var stFId = $("#stIdOne").children('option:selected').val();

                $("#stIdTwo").empty();
                $.ajax({
                    url: '/manage/type/findTypeByStFid',
                    dataType: 'json',
                    type: 'post',
                    data:{stFId:stFId},
                    success: function (data) {
                        $.each(data.data, function (index, item) {
                            $('#stIdTwo').append(new Option(item.stName, item.stId));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");
                    }
                })
            });
        });
    })
</script>
<script>
    //Demo
    layui.use('form', function () {
        var form = layui.form;
        form.render();
        // //监听提交
        // form.on('submit(formDemo)', function(data){
        //     layer.msg(JSON.stringify(data.field));
        //     return false;
        // });
    });
</script>
<script>
    layui.use('element', function () {
        var element = layui.element;

        //获取hash来切换选项卡，假设当前地址的hash为lay-id对应的值
        var layid = location.hash.replace(/^#test1=/, '');
        element.tabChange('test1', layid); //假设当前地址为：http://a.com#test1=222，那么选项卡会自动切换到“发送消息”这一项

        //监听Tab切换，以改变地址hash值
        element.on('tab(test1)', function () {
            location.hash = 'test1=' + this.getAttribute('lay-id');
        });
    });
</script>
<script>
    layui.use(['form', 'layer', 'upload', 'table'], function () {
        var layer = layui.layer;
        var upload = layui.upload;
        var form = layui.form;
        var table = layui.table;
        var $ = layui.jquery;
        var loadingIndex;

        //监听事件
        form.on('select(selectVideos)', function(obj){
            var videoId = obj.value;
            table.render({
                elem: '#sea'
                , url: '/manage/videosItem/findVideoItemByVideoId?videoId=' + videoId //数据接口
                , cols: [[ //表头
                    {field: 'videoItemId', hide:true, title: '视频id'}
                    , {field: 'videoItemName', title: '视频名称'}
                    , {field: 'sort', title: '排序', edit: 'text'}
                ]]
            });
        });

        $("#testListAction").click(function () {
                loadingIndex = layer.load(1, {
                    shade: [0.2,'#000'] //0.1透明度的背景
                });
        });
        upload.render({ //允许上传的文件后缀
            elem: '#test4'
            , url: '/upload/'
            , accept: 'video' //普通文件
            //,exts: 'zip|rar|7z' //只允许上传压缩文件
            , done: function (res) {
                console.log(res)
            }
        });

        //选完文件后自动上传
        upload.render({
            elem: '#videoImg'
            , url: '/manage/videos/uploadVideoImgToOSS'
            //  ,size: 60 //限制文件大小，单位 KB
            , accept: 'images'
            ,acceptMime: 'image/jpg, image/png'
            //, data: {'userId':d.userId,'userDesc':d.userDesc,'videoImg':d.videoImg,'videoName':d.videoName,'stIdOne':d.stIdOne,'stIdTwo':d.stIdTwo}   //可放扩展数据  key-value
            , multiple: true
            , auto: true
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){

                    $('#previewImg').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (res) {
                console.log(res);
                    $('#videoImgSpan').text(res.data);
                    console.log($('#videoImgSpan').text());
                    layer.msg(res.msg,{icon: 1, time: 1000});
                return delete this.files ; //删除文件队列已经上传成功的文件
            }
            ,allDone:function (res) {

            }

        });

        //设定文件大小限制
        upload.render({
            elem: '#test7'
            , url: '/upload/'
            //,size: 60000 //限制文件大小，单位 KB
            , done: function (res) {
                console.log(res)
            }
        });
            //多文件列表示例
            var demoListView = $('#demoList')
                ,files = []
                ,sort = 0
                , uploadListIns = upload.render({
                elem: '#testList'
                // , url: '/manage/videos/uploadFileToOSS'
                , url: '/api/upload/uploadFile'
                //  ,size: 60 //限制文件大小，单位 KB
                , accept: 'video'
                ,acceptMime: 'video/mp4'
                //, data: {'userId':d.userId,'userDesc':d.userDesc,'videoImg':d.videoImg,'videoName':d.videoName,'stIdOne':d.stIdOne,'stIdTwo':d.stIdTwo}   //可放扩展数据  key-value
                , multiple: true
                , auto: true
                , bindAction: '#testListAction'
                ,before:function () {
                   var names = $("div[name='name']");
                   var sorts = $("div[name='sort']");
                   var addVideoItem = [];
                   names.each(function (index) {
                       addVideoItem.push({
                           videoItemName:$(this).html(),
                           sort:sorts.eq(index).html()
                       })
                   });
                    // alert(JSON.stringify(arr))

                    var tableData = layui.table.cache['sea'];
                    this.data = {
                        userId: $('input[name="userId"]').val(),
                        userDesc: $('input[name="userDesc"]').val(),
                        videoImg: $('#videoImgSpan').text(),
                        videoName:$('input[name="videoName"]').val(),
                        videoItemName: $(".layui-table-cell").html(),
                        stIdOne: $('select[name="stIdOne"]').val(),
                        stIdTwo: $('select[name="stIdTwo"]').val(),
                        videoDesc: $('input[name="videoDesc"]').val(),
                        isFree: 0+$('input[name="isFree"]:checked').val(),
                        originalPrice: 0+$('input[name="originalPrice"]').val(),
                        teacherName: $('input[name="teacherName"]').val(),
                        publishType: 0+$('input[name="publishType"]:checked').val(),
                        videoId:  $('select[name="videoId"]').val(),
                        updateVideoItem : JSON.stringify(tableData),
                        addVideoItem : JSON.stringify(addVideoItem)
                    }
                }
                , choose: function (obj) {
                    files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                    //读取本地文件
                    sort = sort+1;
                    console.log(sort);
                    obj.preview(function (index, file,data, result) {
                        //将提交按钮禁用
                        $("#submit").hide();
                        var name = file.name.substr(0,file.name.lastIndexOf("."));
                        var suffix = file.name.substr(file.name.lastIndexOf(".")+1);
                        var tr = $(['<tr id="upload-' + index + '">'
                            , '<td class="table-td demo-edit" ><div  class="layui-table-cell" name="name">'+file.name+'</div></td>'
                            , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                            , '<td class="table-td demo-edit" ><div  class="layui-table-cell" name="sort">'+1+'</div></td>'
                            , '<td  ><div  class="layui-table-cell">正在上传中</div></td>'
                            , '<td>'
                            , '<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>'
                            // , '<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
                            , '</td>'
                            , '</tr>'].join(''));

                        tr.find('.demo-edit').on('click',function(){
                            var e = $(this);
                            var o = e.children(".layui-table-cell");
                            var d = $('<input class="layui-input layui-table-edit">');
                            d[0].value = o.text(), e.find(".layui-table-edit")[0] || e.append(d), d.focus()
                            d.blur(function(){
                                var l = $(this);
                                l.siblings('.layui-table-cell').html(this.value);
                                obj.resetFile(index, file, this.value+'.'+suffix);
                                l.remove();
                            })
                        });

                        //单个重传
                        tr.find('.demo-reload').on('click', function () {
                            obj.upload(index, file);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function () {
                            delete files[index]; //删除对应的文件
                            tr.remove();
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });

                        demoListView.append(tr);
                    });
                }
                , done: function (res, index, upload) {
                    //将提交按钮显示
                    $("#submit").show();
                    // alert(JSON.stringify(res))
                    if(res.code == 200){ //上传成功
                        var tr = demoListView.find('tr#upload-'+ index)
                            ,tds = tr.children();
                        tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
                        tds.eq(4).html(''); //清空操作
                        console.log(res);
                        $('#videoId').html(res.data);
                        console.log($('#videoId').html());

                        var addVideoItemUrlData = [];
                        addVideoItemUrlData.push(res.videoUrl);
                        var data =  $("#addVideoItemUrlData").val();
                        addVideoItemUrlData.push(data);
                        $("#addVideoItemUrlData").val(addVideoItemUrlData);
                        // alert(data);

                        return delete this.files[index] ; //删除文件队列已经上传成功的文件
                    }

                    this.error(index, upload);
                }
                , allDone: function (res, index, upload) {

                    // layer.close(loadingIndex);
                    // layer.msg("上传完成", {icon: 1});
                    // setTimeout(function () {
                    //     var t=$("table tr td").text();
                    //     if (t.indexOf("上传失败") == -1){
                    //         var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                    //         parent.layer.close(index);//关闭弹出的子页面窗口
                    //     }
                    // },1500);

                }
                , error: function (index, upload) {
                    var tr = demoListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(3).html('<span style="color: #FF5722;">上传失败</span>');
                    tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
                }
            });
        });

</script>
</body>
</html>
